//
//  OrderViewController.m
//  Wujin
//
//  Created by cz on 2016/12/11.
//  Copyright © 2016年 dong. All rights reserved.
//

#import "OrderViewController.h"
#import "UserOrderCell.h"
#import "OrderModel.h"
#import "OrderGoodsesCell.h"
#import "MultistageTableView.h"

@interface OrderViewController ()<MTableViewDelegate,MTableViewDataSource>

@property (nonatomic,strong) MultistageTableView *mTableView;

@property (nonatomic,strong) NSMutableArray *orderList;
@property (nonatomic,strong) OrderModel *orderModel;
@property (nonatomic,strong) NSMutableArray *goodesList;

@end

@implementation OrderViewController

- (NSMutableArray *)goodesList {
    if (!_goodesList) {
        _goodesList = [NSMutableArray array];
    }
    return _goodesList;
}

- (NSMutableArray *)orderList {
    if (!_orderList) {
        _orderList = [NSMutableArray array];
    }
    return _orderList;
}

- (MultistageTableView *)mTableView {
    if (!_mTableView) {
        _mTableView = [[MultistageTableView alloc] initWithFrame:CGRectMake(0, 0, SCREENBOUNDS.width, SCREENBOUNDS.height)];
        _mTableView.delegate = self;
        _mTableView.dataSource = self;
        _mTableView.backgroundColor = [UIColor clearColor];
    }
    return _mTableView;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置UI
    [self setupUI];
}

- (void)setupUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.mTableView];
    //给个返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backClick)];
    
    //设置刷新控件
    [self setupRefreshControl];
    //自动刷新控件
    [self.mTableView.tableView.mj_header beginRefreshing];
}

- (NSInteger)numberOfSectionsInTableView:(MultistageTableView *)mTableView {
    
    return self.orderList.count;
}

- (NSInteger)mTableView:(MultistageTableView *)mTableView numberOfRowsInSection:(NSInteger)section {
    
    self.orderModel = self.orderList[section];
    self.goodesList = nil;
    for (NSDictionary *dict in self.orderModel.order_orderGoodses) {
        OrderGoodses *model = [OrderGoodses mj_objectWithKeyValues:dict];
        [self.goodesList addObject:model];
    }
    
    return self.goodesList.count;
}

- (CGFloat)mTableView:(MultistageTableView *)mTableView heightForHeaderInSection:(NSInteger)section {
    
    return 116;
}

- (CGFloat)mTableView:(MultistageTableView *)mTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 92;
}

- (UIView *)mTableView:(MultistageTableView *)mTableView viewForHeaderInSection:(NSInteger)section {
    
    static NSString *reuseId = @"orderCell";
    UserOrderCell *headCell = [mTableView dequeueReusableCellWithIdentifier:reuseId];
    if (!headCell) {
        headCell = [[[NSBundle mainBundle] loadNibNamed:@"UserOrderCell" owner:nil options:nil] lastObject];
    }
    
    headCell.orderModel = self.orderList[section];
    
    UIView *headView = [[UIView alloc] initWithFrame:headCell.bounds];
    [headView addSubview:headCell];
    
    return headView;
}

- (UITableViewCell *)mTableView:(MultistageTableView *)mTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *reuseId = @"goodsCell";
    OrderGoodsesCell *cell = [mTableView dequeueReusableCellWithIdentifier:reuseId];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"OrderGoodsesCell" owner:nil options:nil] lastObject];
    }
    
    cell.orderGoodses = self.goodesList[indexPath.row];
    
    return cell;
}

//- (void)mTableView:(MultistageTableView *)mTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//}

/**
 设置刷新控件
 */
- (void)setupRefreshControl {
    //添加下拉刷新控件
    self.mTableView.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewOrderData)];
    //添加上拉刷新控件
    self.mTableView.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreOrderData)];
}

/**
 加载新的商品数据
 */
- (void)loadNewOrderData {
    
    //一下拉，就停止上拉刷新
    [self.mTableView.tableView.mj_footer endRefreshing];
    //只要一上拉刷新，就把下拉刷新请求的起始页数重置
    i = 2;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"page"] = @(1);
    dict[@"limit"] = @10;    
    dict[@"user_id"] = [WJUser user].user_id;
    
    NSString *url = nil;
    
    if (self.isFinished) {//已完成订单
        url = F(@"%@Index/getFinishedOrderList", BASEURL);
    }else{
        url = F(@"%@Index/getOrderList", BASEURL);
    }
    
    
    
    [FSServer requestWithTarget:url param:dict result:^(id responseObject, NSError *error) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            if ([responseObject[@"flag"] intValue] == 1) {
                NSArray *array = responseObject[@"data"];
                NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, array.count)];
                NSMutableArray *tempA = [NSMutableArray array];
                self.orderList = nil;
                for (NSDictionary *dict in array) {
                    OrderModel *orderModel = [OrderModel yy_modelWithDictionary:dict];
                    
                    [OrderModel mj_setupObjectClassInArray:^NSDictionary *{
                        return @{ @"order_orderGoodses":@"OrderGoodses"};
                    }];
                    
                    [tempA addObject:orderModel];
                }
                [self.orderList insertObjects:tempA atIndexes:indexSet];
                [self.mTableView reloadData];
                //停止刷新
                [self.mTableView.tableView.mj_header endRefreshing];
            }else{
                //停止刷新
                [self.mTableView.tableView.mj_header endRefreshing];
                [MRHud showWithFailure:@"您的网络不给力"];
                DLog(@"没有请求到数据");
            }
        }
    }];
}

/**
 加载更多商品数据
 */

//下拉加载更多的起始页数
static NSInteger i = 2;
//下拉刷新的上限
static NSInteger maxI = 10;

- (void)loadMoreOrderData {
    
    //一上拉，就停止下拉刷新
    [self.mTableView.tableView.mj_header endRefreshing];
    
    if (i > maxI) {//超过10次，就不再加载了
        
        [self.mTableView.tableView.mj_footer endRefreshing];
        [MRHud show];
        [MRHud dismissWithFailure:@"没有更多订单了"];
        return;
    }
        
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"limit"] = @10;
    
    dict[@"page"] = F(@"%ld", (long)i);
    
    dict[@"user_id"] = [WJUser user].user_id;
    
    NSString *url = nil;
    if (self.isFinished) {//已完成订单
        url = F(@"%@Index/getFinishedOrderList", BASEURL);
    }else{
        url = F(@"%@Index/getOrderList", BASEURL);
    }
    
    [FSServer requestWithTarget:url param:dict result:^(id responseObject, NSError *error) {
        NSDictionary *dict = responseObject[@"data"];
        if ([responseObject[@"flag"] intValue] == 1 && dict.count != 0) {
            
            i++;
            
            NSArray *array = responseObject[@"data"];
            NSMutableArray *tempA = [NSMutableArray array];
            
            for (NSDictionary *dict in array) {
                OrderModel *orderModel = [OrderModel yy_modelWithDictionary:dict];
                
                [OrderModel mj_setupObjectClassInArray:^NSDictionary *{
                    return @{ @"order_orderGoodses":@"OrderGoodses"};
                }];
                
                [tempA addObject:orderModel];
            }
            [self.orderList addObjectsFromArray:tempA];
            [self.mTableView reloadData];
            //停止刷新
            [self.mTableView.tableView.mj_footer endRefreshing];
        }else{
            DLog(@"没有请求到数据");
            
            [self.mTableView.tableView.mj_footer endRefreshing];
            [MRHud show];
            [MRHud dismissWithFailure:@"没有更多订单了"];
            
        }
        
    }];
}


- (void)backClick{
    //点击返回隐藏模态窗口
    [self.navigationController popViewControllerAnimated:YES];
}

@end
